<template>
  <div class="view-output">
    <div class="output-table">
      <je-table
        ref="xTable"
        border
        auto-resize
        show-overflow="ellipsis"
        keep-source
        show-header-overflow
        :store="gridStore"
        resizable
        height="100%"
        header-align="center"
        :scroll-y="{ mode: 'wheel' }"
        :row-style="getRowStyle"
        :edit-config="{
          trigger: 'click',
          mode: 'cell',
          showStatus: true,
        }"
      >
        <je-column :title="$t('viewModal.designView.operateCloumn')" width="40" align="center">
          <template #header>
            <i style="font-size: 16px; cursor: pointer" class="fal fa-plus" @click="addColumn"></i>
          </template>
          <template #default="{ row }">
            <i
              style="font-size: 16px; cursor: pointer"
              class="fal fa-times"
              @click="deleteColumn(row)"
            ></i>
          </template>
        </je-column>
        <je-column title="NO." type="seq" width="50" align="center"></je-column>
        <je-column field="tableCode" :title="$t('viewModal.outputView.tableCode')" width="200">
          <template #default="{ row }">
            <span v-html="formatSearchData(row.tableCode)"> </span>
          </template>
        </je-column>
        <je-column field="tableName" :title="$t('viewModal.outputView.tableName')" width="150">
          <template #default="{ row }">
            <span v-html="formatSearchData(row.tableName)"> </span>
          </template>
        </je-column>
        <je-column
          field="column"
          :title="$t('viewModal.outputView.codeColumn')"
          width="220"
          :edit-render="inputRender"
        >
          <template #edit="{ row }">
            <je-input v-model:value.trim="row.column" />
          </template>
          <template #default="{ row }">
            <span v-html="formatSearchData(row.column)"> </span>
          </template>
        </je-column>
        <je-column
          field="name"
          :title="$t('viewModal.outputView.nameColumn')"
          width="220"
          :edit-render="inputRender"
        >
          <template #edit="{ row }">
            <je-input v-model:value.trim="row.name" />
          </template>
          <template #default="{ row }">
            <span v-html="formatSearchData(row.name)"> </span>
          </template>
        </je-column>
        <je-column
          field="value"
          :title="$t('viewModal.outputView.valueColumn')"
          width="220"
          :edit-render="inputRender"
        >
          <template #edit="{ row }">
            <je-input v-model:value.trim="row.value" :disabled="row.type != 'custom'">
              <template #suffix>
                <i class="icon-button fas fa-list-ul" @click="doEditValue(row)"></i>
              </template>
            </je-input>
          </template>
        </je-column>

        <je-column
          field="dataType"
          :title="$t('viewModal.outputView.typeColumn')"
          width="120"
          :edit-render="{}"
        >
          <template #edit="{ row }">
            <je-select
              v-model:value="row.dataType"
              style="width: 100%"
              :disabled="['ID', 'CUSTOMID'].indexOf(row.dataType) != -1"
            >
              <je-select-option
                v-for="item in tableOutputdata.typeOptions"
                :key="item.value"
                :disabled="['ID', 'CUSTOMID', 'CUSTOMFOREIGNKEY'].indexOf(item.value) != -1"
                :value="item.value"
              >
                {{ item.label }}
              </je-select-option>
            </je-select>
          </template>
          <template #default="{ row }">
            {{ getSelectLabel(row.dataType, tableOutputdata.typeOptions) }}
          </template>
        </je-column>
        <je-column
          field="length"
          :title="$t('viewModal.outputView.lengthColumn')"
          width="100"
          :edit-render="inputRender"
        >
          <template #edit="{ row }">
            <je-input
              v-model:value="row.length"
              style="width: 100%"
              :disabled="['ID', 'CUSTOMID'].indexOf(row.dataType) != -1"
            ></je-input>
          </template>
        </je-column>
        <je-column
          field="grouping"
          :title="$t('viewModal.outputView.groupColumn')"
          width="80"
          align="center"
        >
          <template #default="{ row }">
            <je-checkbox v-model:checked="row.grouping" @change="groupColumnChange(row)" />
          </template>
        </je-column>
        <je-column
          field="formula"
          :title="$t('viewModal.outputView.formulaColumn')"
          :edit-render="{}"
          width="100"
        >
          <template #edit="{ row }">
            <je-select
              v-model:value="row.formula"
              allow-clear
              :disabled="row.grouping"
              style="width: 100%"
              @change="xTable.$plugin.updateStatus(scope)"
            >
              <je-select-option
                v-for="item in tableOutputdata.formulaOptions"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </je-select-option>
            </je-select>
          </template>
          <template #default="{ row }">
            {{ getSelectLabel(row.formula, tableOutputdata.formulaOptions) }}
          </template>
        </je-column>
        <je-column
          field="sort"
          :title="$t('viewModal.outputView.orderColumn')"
          :edit-render="{}"
          width="120"
          align="center"
        >
          <template #edit="{ row }">
            <je-select
              v-model:value="row.sort"
              style="width: 100%"
              :disabled="row.grouping"
              @change="xTable.$plugin.updateStatus(scope)"
            >
              <je-select-option
                v-for="item in tableOutputdata.orderOptions"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </je-select-option>
            </je-select>
          </template>
          <template #default="{ row }">
            {{ getSelectLabel(row.sort, tableOutputdata.orderOptions) }}
          </template>
        </je-column>
        <je-column field="whereColum" :edit-render="inputRender">
          <template #header>
            <i class="conditionicon fas fa-question-circle" @click="clickIcon"></i>
            {{ $t('viewModal.outputView.conditionalColumn') }}
          </template>
          <template #edit="{ row }">
            <je-input v-model:value="row.whereColum" :disabled="row.grouping" />
          </template>
        </je-column>
        <template #tbar>
          <div class="title">
            输出列
            <div class="searchInput">
              <je-input-search
                v-model:value="searchValue"
                :placeholder="$t('searchText')"
                style="width: 280px"
                :allow-clear="allowclear"
                :enter-button="$t('searchText')"
                @search="queryTable"
              >
                <template #prefix> <i class="fal fa-search" /> </template> </je-input-search
            ></div>
          </div>
        </template>
      </je-table>
    </div>
  </div>
  <je-modal
    v-model:visible="visibleCondition"
    width="400px"
    title="说明"
    height="auto"
    :resize="false"
    ok-button
    button-align="right"
    :maximizable="false"
  >
    <div>
      <div>条件值编写格式如下：</div>
      <div> 匹配方式+具体的值，例如：=“数值” 或 >3 。</div>
      <div>特殊说明：① 不需要字段编码；② 不支持系统变量。</div>
    </div>
  </je-modal>

  <je-modal
    v-model:visible="editValueModel.editValueVisible"
    width="800px"
    title="值"
    height="600px"
    :resize="false"
    :ok-button="addModule"
    :maximizable="false"
    cancel-button
  >
    <je-textarea v-model:value.trim="editValueModel.textAreaVal" style="height: 100%" />
  </je-modal>
</template>

<script>
  import { defineComponent, ref, watch, reactive, onMounted, nextTick } from 'vue';
  import { Input, Grid, Select, Checkbox, Modal, Data } from '@jecloud/ui';
  import { inputRender, numberRender } from '../../helper/edit-render';
  import { JE_VIEWDESIGN_SELECTOPTIONS } from '@/helper/common';
  import { cloneDeep, isEmpty } from '@jecloud/utils';

  export default defineComponent({
    name: 'OutputView',
    components: {
      JeInput: Input,
      JeInputSearch: Input.Search,
      JeTextarea: Input.TextArea,
      JeTable: Grid,
      JeColumn: Grid.Column,
      JeSelect: Select,
      JeSelectOption: Select.Option,
      JeCheckbox: Checkbox,
      JeModal: Modal,
    },
    props: {
      outPutData: {
        type: Array,
        default: () => {
          return [];
        },
      },
      selectTableDatas: {
        type: Array,
        default: () => {
          return [];
        },
      },
    },
    emits: ['setChangeType', 'getOutputView'],
    setup(props, { emit, expose }) {
      const xTable = ref(null);
      const searchValue = ref('');
      const visibleCondition = ref(false);
      const editValueModel = reactive({
        editValueVisible: false,
        textAreaVal: '',
      });

      const gridStore = Data.Store.useGridStore({
        data: [],
      });

      const tableOutputdata = reactive({
        typeOptions: JE_VIEWDESIGN_SELECTOPTIONS.typeOptions,
        formulaOptions: JE_VIEWDESIGN_SELECTOPTIONS.formulaOptions,
        orderOptions: JE_VIEWDESIGN_SELECTOPTIONS.orderOptions,
      });

      onMounted(() => {
        nextTick(() => {
          emit('getOutputView', getXTable());
          const sortDatas = sortTableData(cloneDeep(props.outPutData));
          gridStore.loadData(sortDatas);
        });
      });

      watch(
        () => searchValue.value,
        (newVal) => {
          if (!newVal) {
            searchType.value = false;
          }
        },
      );

      //搜索
      const queryTable = () => {
        searchType.value = false;
        const tableDatas = cloneDeep(gridStore.data);
        const queryDatas = [],
          oldData = [];
        tableDatas.forEach((item) => {
          if (
            (item.column && item.column.indexOf(searchValue.value.trim()) != -1) ||
            (item.name && item.name.indexOf(searchValue.value.trim()) != -1) ||
            (item.tableCode && item.tableCode.indexOf(searchValue.value.trim()) != -1) ||
            (item.tableName && item.tableName.indexOf(searchValue.value.trim()) != -1)
          ) {
            queryDatas.push(item);
          } else {
            oldData.push(item);
          }
        });
        if (searchValue.value) {
          searchType.value = true;
        }
        gridStore.loadData(queryDatas.concat(oldData));
      };

      //列表单元格格式化
      const getSelectLabel = (value, list, valueProp = 'value', labelField = 'label') => {
        const item = list.find((item) => item[valueProp] === value);
        return item ? item[labelField] : null;
      };
      //获得列表对象
      const getXTable = () => {
        return xTable.value;
      };

      const searchType = ref(false);
      const formatSearchData = (name) => {
        let text = name;
        if (name && name != undefined && searchValue.value.length > 0 && searchType.value) {
          var re = new RegExp(searchValue.value, 'g');
          let replaceString = '<span style="color:red;">' + searchValue.value + '</span>';
          text = name.replace(re, replaceString);
        }
        return text;
      };
      // 列表数据排序
      const sortTableData = (data) => {
        let sortDatas = [];
        if (props.selectTableDatas.length > 0 && data.length > 0) {
          props.selectTableDatas.forEach((item) => {
            const filterData = data.filter((rec) => {
              return rec.tableCode == item.tableCode;
            });
            if (filterData.length > 0) {
              sortDatas = sortDatas.concat(filterData);
            }
          });
          // 自定义的字段
          const customDatas = data.filter((rec) => {
            return rec.type == 'custom' || isEmpty(rec.tableCode);
          });
          sortDatas = customDatas.concat(sortDatas);
        }
        if (sortDatas.length > 0) {
          return sortDatas;
        } else {
          return data;
        }
      };

      // 分组字段值改变
      const groupColumnChange = (row) => {
        if (row.grouping) {
          row.formula = '';
          row.sort = '';
          row.whereColum = '';
        }
      };

      const clickIcon = () => {
        visibleCondition.value = true;
      };
      const selectRow = ref({});
      // 编辑值
      const doEditValue = (row) => {
        if (row.type == 'custom') {
          editValueModel.editValueVisible = true;
          editValueModel.textAreaVal = row.value;
          selectRow.value = row;
        }
      };
      const addModule = () => {
        selectRow.value.value = editValueModel.textAreaVal;
      };

      watch(
        () => gridStore.data,
        () => {
          emit('setChangeType');
        },
        {
          deep: true,
        },
      );
      // 添加数据
      const addColumn = () => {
        const record = {
          tableCode: '',
          tableName: '',
          column: '',
          name: '',
          value: '',
          dataType: 'VARCHAR100',
          length: '',
          grouping: 0,
          formula: '',
          sort: '',
          whereColum: '',
          type: 'custom',
        };
        gridStore.insert(record);
      };
      // 删除数据
      const deleteColumn = (record) => {
        if (record.type == 'custom') {
          gridStore.remove(record);
        } else {
          Modal.alert('仅可删除自定义的数据！', 'error');
        }
      };
      // 改变行样式
      const getRowStyle = ({ row }) => {
        if (row.type == 'custom') {
          return { background: '#faf9da' };
        }
      };
      const doUpdateTableData = (data, records) => {
        const gridData = gridStore.data;
        if (data.type == 'add' && records.length > 0) {
          gridStore.insert(records, -1);
        } else if (data.type == 'addAll') {
          const addRecords = [];
          // 找到不存在数据
          records.forEach((rec) => {
            const value = data.tableCode + '.' + rec.TABLECOLUMN_CODE;
            const flag = gridData.some((item) => {
              return item.value == value;
            });
            if (!flag) {
              var obj = {
                value,
                tableCode: data.tableCode,
                tableName: data.tableName,
                column: rec.TABLECOLUMN_CODE,
                name: rec.TABLECOLUMN_NAME,
                dataType: rec.TABLECOLUMN_TYPE,
                length: rec.TABLECOLUMN_LENGTH,
                grouping: false,
                sort: '',
                formula: '',
                whereColum: '',
              };
              addRecords.push(obj);
            }
          });
          gridStore.insert(addRecords, -1);
        } else if (data.type == 'delete' && records.length > 0) {
          const removeRecords = gridData.filter((item) => {
            return records.includes(item.value);
          });
          gridStore.remove(removeRecords);
        } else if (data.type == 'deleteTable') {
          const removeRecords = [];
          gridData.forEach((rec) => {
            if (rec.tableCode == data.tableCode) {
              removeRecords.push(rec);
            }
          });
          gridStore.remove(removeRecords);
        }
      };
      expose({
        doUpdateTableData,
      });
      return {
        searchValue,
        queryTable,
        tableOutputdata,
        getSelectLabel,
        xTable,
        allowclear: true,
        inputRender,
        numberRender,
        formatSearchData,
        searchType,
        groupColumnChange,
        visibleCondition,
        clickIcon,
        doEditValue,
        editValueModel,
        addModule,
        addColumn,
        deleteColumn,
        getRowStyle,
        gridStore,
      };
    },
  });
</script>

<style lang="less" scoped>
  .view-output {
    height: 100%;
    .title {
      height: 40px;
      background: #f7f9fc;
      line-height: 40px;
      font-size: 14px;
      padding: 0 16px;
      color: #3265f5;
      border-top: 1px solid #e6e6e6;
      border-bottom: 1px solid #e6e6e6;
      position: relative;
    }
    //border-top: 1px solid #e6e6e6;

    .output-table {
      height: 100%;
      .conditionicon {
        color: #ebebeb;
        cursor: pointer;
        margin-right: 5px;
        &:hover {
          color: #3265f5;
        }
      }
    }
  }
</style>
<style lang="less">
  .view-output {
    .title {
      .searchInput {
        height: 40px;
        // border-color: #e6e6e6 !important;
        border-radius: 0;
        position: absolute;
        right: 20px;
        margin-top: 3px;
        display: inline-block;
      }
      .ant-input-search-button {
        width: 60px;
      }
      .ant-input-search {
        border-bottom-right-radius: 0;
        border-top-right-radius: 0;
      }
      .ant-input-search.ant-input-affix-wrapper:hover {
        border: 1px solid #5c8dff !important;
        box-shadow: none !important;
      }
      .ant-input-search.ant-input-affix-wrapper-focused {
        border: 1px solid #5c8dff !important;
        box-shadow: none !important;
      }
    }
  }
</style>
